import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Table, Button, Modal, message, Flex, Dropdown, ConfigProvider } from 'antd';
import type { TableProps, TableColumnType } from 'antd';
import { PlusOutlined, DownOutlined, DeleteOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import axios from 'axios';
import './style.css';
interface DataType {
  key: React.Key;
  content: string;
  type: string;
}

interface TableParams {
  pagination: {
    current: number;
    pageSize: number;
  };
  type?: string;
}
interface DTableProps {
  Qtype: string; // 'all' | 'single' | 'multi' | 'code'
  keyword?: string;
  onSearch?: (kw: string) => void;
}

const DTable: React.FC<DTableProps> = ({ Qtype, keyword = '' }) => {
  const navigate = useNavigate(); //导航
  const [data, setData] = useState<DataType[]>([]);
  const [loading, setLoading] = useState(false);
  const [tableParams, setTableParams] = useState<TableParams>({
    pagination: {
      current: 1,
      pageSize: 5
    },
    type: ''
  });
  const [total, setTotal] = useState(0);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [deleteLoding, setDeleteLoading] = useState(false);
  const fetchData = async () => {
    setLoading(true);
    try {
      const response = await axios.get('/api/questions', {
        params: {
          type: Qtype === '全部' ? '' : Qtype,
          keyword: keyword,
          pagenum: tableParams.pagination.current,
          pagesize: tableParams.pagination.pageSize
        }
      });

      if (response.data.code === 0) {
        setData(
          response.data.data.map((item: any) => ({
            key: item.id,
            content: item.content,
            type: item.type // 统一用type
          }))
        );
        setTotal(response.data.page.total);
      } else {
        console.error('API Error:', response.data.message);
      }
    } catch (error) {
      console.error('Error fetching data:', error);
    }
    setLoading(false);
  };

  // Qtype和keyword变化时也要重新请求
  useEffect(() => {
    fetchData();
  }, [tableParams.pagination.current, tableParams.pagination.pageSize, Qtype, keyword]);

  // 分页变化时也要重新请求
  const handleTableChange: TableProps<DataType>['onChange'] = (pagination) => {
    setTableParams({
      ...tableParams,
      pagination: {
        current: pagination.current || 1,
        pageSize: pagination.pageSize || 5
      }
    });
  };

  const handleEdit = (id: React.Key) => {
    console.log('Edit button clicked, id:', id);
    const path = `/question-bank/edit-question/${id}`;
    console.log('Navigating to:', path);
    navigate(path);
  };
  // 删除
  const handleDelete = (id: React.Key) => {
    console.log('handleDelete', id);
    Modal.confirm({
      title: '确认删除该题目？',
      cancelText: '取消',
      okText: '确定',
      centered: true,
      closable: true,
      keyboard: true,
      onOk: async () => {
        setDeleteLoading(true);
        console.log('onOk called');
        try {
          await axios.delete('/api/questions', { params: { ids: id } });
          message.success('删除成功');
          fetchData();
        } catch (e) {
          message.error('删除失败');
        }
        setDeleteLoading(false);
      }
    });
  };
  // 批量删除
  const handleBatchDelete = () => {
    Modal.confirm({
      title: '确认批量删除选中题目？',
      cancelText: '取消',
      okText: '确定',
      centered: true,
      closable: true,
      keyboard: true,
      onOk: async () => {
        setDeleteLoading(true);
        try {
          await axios.delete('/api/questions', { params: { ids: selectedRowKeys.join(',') } });
          message.success('批量删除成功');
          setSelectedRowKeys([]);
          fetchData();
        } catch (e) {
          message.error('批量删除失败');
        }
        setDeleteLoading(false);
      }
    });
  };
  // 表格多选
  const rowSelection: TableProps<DataType>['rowSelection'] = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
    }
  };

  const RemoveButtonStyle: React.FC<{ text: string; nav: string }> = ({ text, nav }) => {
    
    const handleSwitch = () => {
      navigate(`/question-bank/${nav}`);
    };
    return (
      <ConfigProvider wave={{ disabled: true }}>
        <Button
          type="default"
          style={{ width: '100%', border: 'none', backgroundColor: 'transparent' }}
          block
          onClick={handleSwitch}
        >
          {text}
        </Button>
      </ConfigProvider>
    );
  };
  const items: MenuProps['items'] = [
    {
      key: '1',
      label: <RemoveButtonStyle text="AI出题" nav="ai-question" />
    },
    {
      key: '2',
      label: <RemoveButtonStyle text="自主出题" nav="set-question" />
    },
  ];
  const columns: TableColumnType<DataType>[] = [
    {
      title: '题目',
      dataIndex: 'content'
    },
    {
      title: '题型',
      dataIndex: 'type'
    },
    {
      title: '操作',
      align: 'center',
      render: (_, record) => (
        <>
          <Button type="link" onClick={() => handleEdit(record.key)}>
            编辑
          </Button>
          <Button type="link" danger onClick={() => handleDelete(record.key)}>
            删除
          </Button>
        </>
      )
    }
  ];
  return (
    <div style={{margin:10,marginRight:5 }}>
      <div style={{ marginBottom: 16 }}>
        <Flex justify="end" align="center" gap="small">
          <Dropdown placement="bottomLeft" menu={{ items }} arrow>
            <Button type="primary" icon={<PlusOutlined />}>
              出题
              <DownOutlined />
            </Button>
          </Dropdown>
          <Button
            danger
            disabled={selectedRowKeys.length === 0}
            loading={deleteLoding}
            onClick={handleBatchDelete}
            icon={<DeleteOutlined />}
          >
            批量删除
          </Button>
        </Flex>
      </div>
      <Table<DataType>
        rowSelection={rowSelection}
        columns={columns}
        dataSource={data}
        size="small"
        loading={loading}
        pagination={{
          className: 'pageDivCss',
          align: 'end',
          total: total,
          pageSize: tableParams.pagination.pageSize,
          current: tableParams.pagination.current,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条`,
          pageSizeOptions: ['5', '10', '20', '50', '100'],
          locale: {
            items_per_page: '条/页',
            jump_to: '跳至',
            page: '页'
          }
        }}
        onChange={handleTableChange}
      />
    </div>
  );
};

export default DTable;
